import { Promise } from "core-js"
import axios from "axios";
import qs from "qs";


var request = {
    request: function (url, method, data, that) {

        return new Promise((resove, reject) => {

            axios.interceptors.response.use(res => {
                // 对响应数据做些什么
                return res;
            }, err => {
                // 对响应错误做些什么
            	// 对错误响应进行拦截过滤
            	let msg = err.response.data.msg;
                let status = err.response.status;
                // that.$message.error(msg || "进入拦截器")
                if (status == 401) {
                    that.$message.error("登录失效，请重新登陆");
                    localStorage.clear();
                    window.location.href = window.location.origin;
                }
                that.$message.error(msg || "抱歉，出错啦")
                return Promise.reject(err)
            })
            let temp = localStorage.getItem("user");
            let user = temp ? JSON.parse(temp) : null;
            //console.log(user);
            data.token = user ? user.token : '';
            //console.log(user);
            if (!data.role) {
                data.role = localStorage.getItem("role") ? localStorage.getItem("role") : '';
            }
            data.userId = user ? user.user.id : '';
            axios({
                url: "http://localhost:8081/" + url,
                method: method.toLocaleUpperCase(),
                data: qs.stringify(data),
            }).then(data => {
                //console.log(data);
                resove(data);
            }).catch((err) => {
                reject(err);
            })
        })
    }
}

export { request }